package net.qhzw.vip.qiyu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import net.qhzw.vip.qiyu.entity.Shop;
import net.qhzw.vip.qiyu.entity.SysCommunity;
import net.qhzw.vip.qiyu.entity.SysRole;
import net.qhzw.vip.qiyu.entity.SysUser;
import net.qhzw.vip.qiyu.handler.ApiException;
import net.qhzw.vip.qiyu.mapper.ShopMapper;
import net.qhzw.vip.qiyu.result.PageResult;
import net.qhzw.vip.qiyu.service.ShopService;
import net.qhzw.vip.qiyu.service.SysCommunityService;
import net.qhzw.vip.qiyu.service.SysRoleService;
import net.qhzw.vip.qiyu.service.SysUserService;
import net.qhzw.vip.qiyu.util.PageAdapter;
import net.qhzw.vip.qiyu.util.PinyinUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements ShopService {


    @Autowired
    private ShopMapper shopMapper;


    @Autowired
    private SysRoleService roleService;

    @Autowired
    private SysUserService userService;

    @Autowired
    private SysCommunityService communityService;


    @Override
    public PageResult<Shop> findByPage(Page<Shop> page, String shopName) {
        List<Shop> shopList = shopMapper.findByPage(new PageAdapter(page), shopName);
        long total = shopMapper.totalByPage(shopName);
        return new PageResult<Shop>(total, shopList);
    }


    /**
     * 添加商铺
     *
     * @param userId
     * @param shop
     * @return
     */
    @Override
    @Transactional
    public boolean addShop(Long userId, Shop shop) {
        checked(shop);
        shop.setShopId(IdWorker.getId());
        if (shop.getShopType() != null && shop.getShopType() == 1){
            addUser(userId, shop);
            addCommunity(userId, shop);
            addRole(userId, shop);
        }else {
            addUser(userId, shop);
        }
        addInformation(shop.getShopId(), shop.getShopName());
        shop.setStatus((byte) 1);
        return save(shop);
    }

    private void addInformation(Long shopId, String shopName) {
        shopMapper.insertInformation(shopId, shopName);
    }

    /**
     * 修改商铺状态
     *
     * @param shop
     * @return
     */
    @Override
    @Transactional
    public boolean setStatus(Shop shop) {
        Byte status = shop.getStatus();
        userService.updateStatus(shop.getShopId(), status);
        return updateById(shop);
    }

    @Override
    public String getWxMchIdById(Long shopId) {
        return shopMapper.getWxMchIdById(shopId);
    }

    @Override
    public boolean setIsShow(List<String> uids) {
       List<Shop> shops = new ArrayList<>();
        for (String uid : uids) {
            Shop shop = new Shop();
            shop.setIsShow((byte) 1);
            shop.setShopId(Long.valueOf(uid));
            shops.add(shop);
        }

        return updateBatchById(shops);
    }

    @Override
    public boolean setStatusShow(Shop shop) {
        //Byte isShow = shop.getIsShow();
        //userService.updateStatus(shop.getShopId(), isShow);
        return updateById(shop);
    }


    private void checked(Shop shop) {
        int shopNameCount = count(new LambdaQueryWrapper<Shop>().eq(Shop::getShopName, shop.getShopName()));
        int shortNameCount = count(new LambdaQueryWrapper<Shop>().eq(Shop::getShortName, shop.getShortName()));
        if (shopNameCount > 0) {
            throw new ApiException("商铺名称已存在!");
        }
        if (shortNameCount > 0) {
            throw new ApiException("商铺简称已存在!");
        }
    }


    /**
     * 添加角色
     */
    private void addRole(Long operateUserId, Shop shop){
        //添加角色
        SysRole sysRole = new SysRole();
        long roleId = IdWorker.getId();
        sysRole.setId(roleId);
        sysRole.setShopId(shop.getShopId());
        sysRole.setName(shop.getShopName() + "管理员");
        sysRole.setCode(PinyinUtils.toPinyin(shop.getShortName()) + "_ADMIN");
        sysRole.setDescription(shop.getShortName() + "管理");
        sysRole.setCreateBy(operateUserId);
        sysRole.setStatus((byte) 1);
        sysRole.setCreated(new Date());
        roleService.save(sysRole);
    }

    /**
     * 添加站点
     */
    private void addCommunity(Long operateUserId, Shop shop){
        SysCommunity community = new SysCommunity();
        long communityId = IdWorker.getId();
        community.setId(communityId);
        String shortName = shop.getShortName();
        community.setShopId(shop.getShopId());
        community.setName("仓库");
        community.setSiteManager("仓库");
        community.setSiteMobile("仓库");
        community.setRealName("仓库");
        community.setBank("仓库");
        community.setBankAddr("仓库");
        community.setStatus((byte) 1);
        community.setAddress("仓库");
        community.setBankCard("仓库");
        community.setBusinessType((byte) -1);
        community.setRemake("此条数据为绑定" + shortName + "车辆默认所在位置的数据，禁止做任何编辑，修改操作");
        communityService.save(community);
    }


    /**
     * 添加角色|用户
     *
     * @param operateUserId
     * @param shop
     */
    private void addUser(Long operateUserId, Shop shop) {
//        SysCommunity community = new SysCommunity();
//        long communityId = IdWorker.getId();
//        community.setId(communityId);
//        String shortName = shop.getShortName();
//        community.setShopId(shop.getShopId());
//        community.setName("仓库");
//        community.setSiteManager("仓库");
//        community.setSiteMobile("仓库");
//        community.setRealName("仓库");
//        community.setBank("仓库");
//        community.setBankAddr("仓库");
//        community.setStatus((byte) 1);
//        community.setAddress("仓库");
//        community.setBankCard("仓库");
//        community.setBusinessType((byte) -1);
//        community.setRemake("此条数据为绑定" + shortName + "车辆默认所在位置的数据，禁止做任何编辑，修改操作");
//        communityService.save(community);

        //添加角色
//        SysRole sysRole = new SysRole();
//        long roleId = IdWorker.getId();
//        sysRole.setId(roleId);
//        sysRole.setShopId(shop.getShopId());
//        sysRole.setName(shop.getShopName() + "管理员");
//        sysRole.setCode(PinyinUtils.toPinyin(shop.getShortName()) + "_ADMIN");
//        sysRole.setDescription(shop.getShortName() + "管理");
//        sysRole.setCreateBy(operateUserId);
//        sysRole.setStatus((byte) 1);
//        sysRole.setCreated(new Date());
//        roleService.save(sysRole);

        int userCount = userService.count(new LambdaQueryWrapper<SysUser>()
                .eq(SysUser::getUsername, shop.getAdminAccount()));
        if (userCount > 0) {
            throw new ApiException(shop.getAdminAccount() + "用户已经存在!");
        }
        //添加用户
        SysUser sysUser = new SysUser();
        long userId = IdWorker.getId();
        sysUser.setId(userId);
        sysUser.setParentId(0L);
        sysUser.setShopId(shop.getShopId());
        sysUser.setCompanyId(1L);
        sysUser.setCommunityId(1L);
        sysUser.setStieId(1L);
        sysUser.setUsername(shop.getAdminAccount());
        sysUser.setPassword(new BCryptPasswordEncoder().encode(shop.getAdminPassword()));
        sysUser.setFullname(shop.getShopName());
        sysUser.setMobile(shop.getMobile());
        sysUser.setEmail(shop.getEmail());
        sysUser.setStatus((byte) 1);
        sysUser.setCreateBy(operateUserId);
        sysUser.setCreated(new Date());
        //sysUser.setRoleId(roleId);
        userService.save(sysUser);
    }


}
